package com.xiaoqi.api.service.Imp;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaoqi.api.constant.StatusConst;
import com.xiaoqi.api.dto.EngineerDTO;
import com.xiaoqi.api.dto.UserDto;
import com.xiaoqi.api.mapper.EngineerMapper;
import com.xiaoqi.api.pojo.Engineer;
import com.xiaoqi.api.query.EngineerQuery;
import com.xiaoqi.api.service.EngineerService;

import com.xiaoqi.api.utlis.PageResult;
import com.xiaoqi.api.vo.EngineerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Component
public class EngineerServiceImp implements EngineerService {

    @Value("${xiaoqi.password")
    private String password;

    @Resource
    EngineerMapper engineerMapper;


    @Override
    public EngineerVO login(String loginName, String password) {
        //密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        return engineerMapper.login(loginName,password);
    }

    @Override
    public void add(EngineerDTO engineerDTO) {
        Engineer engineer = new Engineer();
        BeanUtils.copyProperties(engineerDTO,engineer);
        engineer.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));

        engineer.setStatus(StatusConst.ACTIVE_STATUS);
        engineerMapper.add(engineer);
    }

    @Override
    public PageResult<EngineerVO> find(EngineerQuery engineerQuery) {
        PageHelper.startPage(engineerQuery.getPage(),engineerQuery.getPageSize());  //告诉PageHelper此处需要分页

        Page<EngineerVO> page = (Page<EngineerVO>) engineerMapper.find(engineerQuery);

        PageInfo<EngineerVO> pageInfo = page.toPageInfo();


        List<EngineerVO> engineerVOList = pageInfo.getList();
        long total = pageInfo.getTotal();

        PageResult<EngineerVO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setList(engineerVOList);

        return pageResult;
    }

    @Override
    public void update(long id, EngineerDTO engineerDTO) {
        Engineer engineer = new Engineer();
        BeanUtils.copyProperties(engineerDTO,engineer);

        engineer.setId(id);
        engineerMapper.update(engineer);
    }

    @Override
    public void updateStatus(long id, byte status) {
        Engineer engineer = new Engineer();
        engineer.setId(id);
        engineer.setStatus(status);
        engineerMapper.update(engineer);
    }

    @Override
    public EngineerVO findById(long id) {
        return engineerMapper.findById(id);
    }

}
